<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/>




  <link href="//fonts.googleapis.com/css?family=Lato:300,400,700,400italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">



<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=0.5.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="算法,NOIP,教案," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=0.5.0" />






<meta name="description" content="我们要学习的排序算法有: 冒泡排序,归并排序,快速排序,使用C++的sort.
冒泡排序冒泡排序是很简单的算法,这里我们看一下它的原是就可以了

通过的上面的图片我们可以等到下面的信息:

每一趟排序都是把最值排序在后面
对于有n个数的数组来说,要排序n-1趟
n个数字只n-1个数字就可以了,最后一个数字自动就在第一位


对第1趟排序的范围是a[1]--&amp;gt;a[n-1]
对第2趟排序的范围是">
<meta property="og:type" content="article">
<meta property="og:title" content="排序算法学习">
<meta property="og:url" content="http://yoursite.com/2016/04/基础算法1/index.html">
<meta property="og:site_name" content="Rainboy">
<meta property="og:description" content="我们要学习的排序算法有: 冒泡排序,归并排序,快速排序,使用C++的sort.
冒泡排序冒泡排序是很简单的算法,这里我们看一下它的原是就可以了

通过的上面的图片我们可以等到下面的信息:

每一趟排序都是把最值排序在后面
对于有n个数的数组来说,要排序n-1趟
n个数字只n-1个数字就可以了,最后一个数字自动就在第一位


对第1趟排序的范围是a[1]--&amp;gt;a[n-1]
对第2趟排序的范围是">
<meta property="og:image" content="http://yoursite.com/images/冒泡排序.png">
<meta property="og:image" content="http://yoursite.com/images/归并排序.png">
<meta property="og:image" content="http://yoursite.com/images/归并排序2.png">
<meta property="og:image" content="http://yoursite.com/images/快速排序.png">
<meta property="og:image" content="http://yoursite.com/images/快速排序2.png">
<meta property="og:updated_time" content="2016-04-09T23:57:11.113Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="排序算法学习">
<meta name="twitter:description" content="我们要学习的排序算法有: 冒泡排序,归并排序,快速排序,使用C++的sort.
冒泡排序冒泡排序是很简单的算法,这里我们看一下它的原是就可以了

通过的上面的图片我们可以等到下面的信息:

每一趟排序都是把最值排序在后面
对于有n个数的数组来说,要排序n-1趟
n个数字只n-1个数字就可以了,最后一个数字自动就在第一位


对第1趟排序的范围是a[1]--&amp;gt;a[n-1]
对第2趟排序的范围是">
<meta name="twitter:image" content="http://yoursite.com/images/冒泡排序.png">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"hide"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: 'Author'
    }
  };
</script>

  <title> 排序算法学习 | Rainboy </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh_Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Rainboy</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-home fa-fw"></i> <br />
            
            Startseite
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-th fa-fw"></i> <br />
            
            Kategorien
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-archive fa-fw"></i> <br />
            
            Archiv
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-tags fa-fw"></i> <br />
            
            Tags
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                排序算法学习
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Veröffentlicht am</span>
            <time itemprop="dateCreated" datetime="2016-04-09T20:00:00+08:00" content="2016-04-09">
              2016-04-09
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">in</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/NOIP教程/" itemprop="url" rel="index">
                    <span itemprop="name">NOIP教程</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/04/基础算法1/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/04/基础算法1/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>我们要学习的排序算法有: <strong>冒泡排序</strong>,<strong>归并排序</strong>,<strong>快速排序</strong>,<strong>使用C++的sort</strong>.</p>
<h2 id="冒泡排序"><a href="#冒泡排序" class="headerlink" title="冒泡排序"></a>冒泡排序</h2><p>冒泡排序是很简单的算法,这里我们看一下它的原是就可以了</p>
<p><img src="/images/冒泡排序.png" alt="冒泡排序"></p>
<p>通过的上面的图片我们可以等到下面的信息:</p>
<ol>
<li>每一趟排序都是把最值排序在后面</li>
<li>对于有<strong>n</strong>个数的数组来说,要排序<strong>n-1</strong>趟<ul>
<li>n个数字只<strong>n-1</strong>个数字就可以了,最后一个数字自动就在第一位</li>
</ul>
</li>
<li>对第1趟排序的范围是<code>a[1]--&gt;a[n-1]</code></li>
<li>对第2趟排序的范围是<code>a[1]--&gt;a[n-2]</code></li>
<li>对第i趟排序的范围是<code>a[1]--&gt;a[n-i]</code></li>
</ol>
<p><strong>一句话算法：第一趟循环len-1次,第二趟循环len-2次,第i趟循环len-i次</strong></p>
<h3 id="bubble-sort代码核心代码"><a href="#bubble-sort代码核心代码" class="headerlink" title="bubble_sort代码核心代码"></a>bubble_sort代码核心代码</h3><pre><code>void bubble_sort(int a[],int len){
    int i=len,j;
    for(i=1;i&lt;=len-1;i++)
        for(j=1;j&lt;=len-i;j++){
            if(a[j] &gt; a[j+1]){
                tmp =a[j];
                a[j] =a[j+1]
                a[j+1]=tmp;
            }
        }
}
</code></pre><h2 id="归并排序"><a href="#归并排序" class="headerlink" title="归并排序"></a>归并排序</h2><p>原理如下:</p>
<p><img src="/images/归并排序.png" alt="归并排序1"></p>
<p>我们发现<strong>归并排序</strong>原理就是:对原来<strong>已经有序</strong>的两个数组就合并操作(取两个头部比较)后还是有序.</p>
<p>简单的说归并排序就是:<strong>从两个有序数组的头部开始取,谁小就取谁</strong></p>
<p>那我们的代码如下:</p>
<pre><code>#include &lt;cstdio&gt;

int a[] = {1,3,7};
int b[] = {2,5,6};
int tmp[100];

int merge(){
    int i=0,j=0;//i,j分别指向a,b的头部
    int k=0;//k是tmp数的下标
    int len_a = sizeof(a)/sizeof(a[0]); //a的长度
    int len_b = sizeof(b)/sizeof(b[0]);//b的长度

    while(i&lt; len_a &amp;&amp; j&lt; len_b){
        if(a[i] &lt; b[j]){
            tmp[k]=a[i];i++;k++;
        } else{
            tmp[k]=b[j];j++;k++;
        }
    }
    while(i&lt;len_a) {tmp[k++] = a[i];i++;}; //复制a数组的剩余
    while(j&lt;len_b) {tmp[k++] = b[j];j++;}; //复制b数组的剩余
}

int main(){

    merge();

    int i;
    int len_a = sizeof(a)/sizeof(a[0]); //a的长度
    int len_b = sizeof(b)/sizeof(b[0]);//b的长度
    for(i=0;i&lt;len_a+len_b;i++)
        printf(&quot;%d &quot;,tmp[i]);
    return 0;
}
</code></pre><p>这里有一个问题:如果我们的数组只有一个,如何使用归并排序?</p>
<p>很简单,我们只要把数组tmp里的值再赋值给原数组就可以了!</p>
<p><img src="/images/归并排序2.png" alt="归并排序2"></p>
<p>完整的代码</p>
<pre><code>/* 
 *  算法思想:
 *      分治
 * */

#include &lt;cstdio&gt;

int a[] ={1,7,3,6,5,2};
int tmp[100]; //临时存储的中间数组

void merge_sort(int s,int t){
        //s =start t=T
    int mid,i,j,k;

    if(s==t) return ; //如果区间只有一个数,就返回

    mid = (s+t)&gt;&gt;1; //取中间的点
    merge_sort(s,mid);
    merge_sort(mid+1,t);

    i=s;
    j=mid+1;
    k=s;

    while(i&lt;=mid &amp;&amp; j&lt;=t){
        if( a[i] &lt;=a[j]){
            tmp[k]=a[i];k++;i++;
        } else {
            tmp[k]=a[j];j++;k++;
        }
    }

    while(i&lt;=mid) { tmp[k]=a[i];k++;i++;};
    while(j&lt;=t)   { tmp[k]=a[j];k++;j++;};

    for(i=s;i&lt;=t;i++)
        a[i]=tmp[i];
}

int main()
{
    merge_sort(0,sizeof(a)/sizeof(a[0])-1);
    int i;
    for(i=0;i&lt;sizeof(a)/sizeof(a[0]);i++)
        printf(&quot;%d &quot;,a[i]);
    return 0;
}
</code></pre><h2 id="快速排序"><a href="#快速排序" class="headerlink" title="快速排序"></a>快速排序</h2><p><strong>快速排序的基本思想:</strong> 通过一趟排序将数组分成两个部分,其中一个部分都比<strong>关键字</strong>小,另一个部分都比<strong>关键字</strong>大,然后再分别对这两部分进行这种操作,最后就可以达到全部有序.通常我们取待排序部分的第一个值为<strong>关键字</strong>.</p>
<p><img src="/images/快速排序.png" alt="快速排序1"></p>
<p>我们能不能把步骤想的更具体一点,怎么样做才能把数分成这样的两个部分?</p>
<p><img src="/images/快速排序2.png" alt="快速排序"></p>
<p>上面的图片解释了一趟快速排序的原理,如果你有足够的想想象力,可以把红色,蓝色下标想象成两个<strong>机器人,它们不停的移动去判断值,一但符合条件,就把箱子里的值仍给另一个机器人,自己停止,另一个机器人又开始工作</strong>,这样的不停往返的下去,就可以把数分成两个部分了.</p>
<p>快速排序代码</p>
<pre><code>/* 
 *   快速排序本质:
 *      用key值,把数据分成两个部分,一部分比较key小,一部分比key大
 * */

#include &lt;cstdio&gt;

int a[]={6,2,7,3,8,9};

void quicksort(int l,int r){
    int s=l,t=r;
    int key =a[l]; // 取第一个值为key

    while(s &lt; t){
        while( s &lt;t &amp;&amp; a[t] &gt;= key) --t;// 如果a[t] &gt;= key,t下标不停变小,直到a[t] &lt; key
        if(s &lt; t) a[s++] = a[t];        //停下来的时候,看一看,是不是到中点,如果不是 交换值
        while(s&lt;t &amp;&amp; a[s] &lt;= key) ++s;  //如果a[s] &lt;= key  s的下标不停变大,直到a[s] &gt; key
        if(s&lt;t ) a[t--] = a[s];         //停下来的时候,看一看,是不是到了中点,如果不是,交换值
    }
    a[s] = key;  //上面while停止的时候,一定是s ==t
    quicksort(l,s-1);
    quicksort(s+1,r);
}

int main(){
    int len_a = sizeof(a)/sizeof(a[0]);
    quicksort(0,len_a-1);
    return 0;
}
</code></pre><h2 id="C-内部函数-sort"><a href="#C-内部函数-sort" class="headerlink" title="C++内部函数 sort"></a>C++内部函数 sort</h2><p>下面的我们来使用C++本身给我们提供的排序函数.</p>
<pre><code>sort(a+m,a+n);      //[a+m,a+n) 范围内的元素进行排序
sort(a+m,a+n,cmp); //cmp 是函数
</code></pre><p>样例代码</p>
<pre><code>#include &lt;cstdio&gt;
#include &lt;algorithm&gt;
using namespace std;

int a[100];
int main(){
    int i;
    for (i=0;i&lt;10;i++){ //输入10个数
        scanf(&quot;%d&quot;,&amp;a[i]);
    }

    sort(a+0,a+10); //数组名+数字的本质是指针操作
    for(i=0;i&lt;10;i++)
        printf(&quot;%d &quot;,a[i]);

    return 0;
}
</code></pre><p>如果我们想让从大到小排序怎么办?</p>
<pre><code>#include &lt;cstdio&gt;
#include &lt;algorithm&gt;
using namespace std;

int a[100];

/* 原是是为真的时候,第一个数字放前面 */
int mycmp(int &amp;a,int &amp;b){ 
    if(a &gt; b)
        return 1;
    return 0;
}

int main(){
    int i;
    for (i=0;i&lt;10;i++){ //输入10个数
        scanf(&quot;%d&quot;,&amp;a[i]);
    }

    sort(a+0,a+10,mycmp); //数组名+数字的本质是指针操作
    for(i=0;i&lt;10;i++)
        printf(&quot;%d &quot;,a[i]);

    return 0;
}
</code></pre><h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><ul>
<li><a href="http://cojs.tk/cogs/problem/problem.php?pid=74" target="_blank" rel="external">明明的随机数</a></li>
<li><a href="http://www.rqnoj.cn/problem/350" target="_blank" rel="external">找第k小的数</a></li>
<li><a href="http://cojs.tk/cogs/problem/problem.php?pid=122" target="_blank" rel="external">NOIP2007奖学金</a></li>
<li><a href="http://cojs.tk/cogs/problem/problem.php?pid=76" target="_blank" rel="external">NOIP2007统计数字</a></li>
<li><a href="http://www.rqnoj.cn/problem/353" target="_blank" rel="external">列队</a></li>
<li>待加入</li>
</ul>

      
    </div>

    <div>
      
        
      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/算法/" rel="tag">#算法</a>
          
            <a href="/tags/NOIP/" rel="tag">#NOIP</a>
          
            <a href="/tags/教案/" rel="tag">#教案</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/04/warehouse学习笔记/" rel="next" title="warehouse学习笔记">
                <i class="fa fa-chevron-left"></i> warehouse学习笔记
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/04/基础算法1/"
           data-title="排序算法学习" data-url="http://yoursite.com/2016/04/基础算法1/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Inhaltsverzeichnis
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Übersicht
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Rainboy" />
          <p class="site-author-name" itemprop="name">Rainboy</p>
          <p class="site-description motion-element" itemprop="description">Rainboy Personal Blog by Hexo</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">16</span>
              <span class="site-state-item-name">Artikel</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">Kategorien</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">23</span>
                <span class="site-state-item-name">Tags</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        <div class="links-of-blogroll motion-element">
          
        </div>

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator">
            <i class="fa fa-angle-double-up"></i>
          </div>
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#冒泡排序"><span class="nav-number">1.</span> <span class="nav-text">冒泡排序</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#bubble-sort代码核心代码"><span class="nav-number">1.1.</span> <span class="nav-text">bubble_sort代码核心代码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#归并排序"><span class="nav-number">2.</span> <span class="nav-text">归并排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#快速排序"><span class="nav-number">3.</span> <span class="nav-text">快速排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#C-内部函数-sort"><span class="nav-number">4.</span> <span class="nav-text">C++内部函数 sort</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#题目"><span class="nav-number">5.</span> <span class="nav-text">题目</span></a></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator">
            <i class="fa fa-angle-double-down"></i>
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Rainboy</span>
</div>

<div class="powered-by">
  Erstellt mit  <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>



      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  


  




<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=0.5.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=0.5.0"></script>



  
  

  
  
<script type="text/javascript" src="/js/src/scrollspy.js?v=0.5.0"></script>

<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 1 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = NexT.utils.escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    NexT.motion.middleWares.sidebar = function () {
      var $tocContent = $('.post-toc-content');

      if (CONFIG.sidebar.display === 'post' || CONFIG.sidebar.display === 'always') {
        if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
          NexT.utils.displaySidebar();
        }
      }
    };
  });
</script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=0.5.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"rainboy"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
  





  
  
  
  <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
  </script>

  <script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for (i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  </script>

  
    <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
